package com.bw.lib_common.mvi

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.youth.banner.util.LogUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

abstract class BaseViewModel<intent:UIIntent>:ViewModel() {
    private val _intent = Channel<UIIntent> { Channel.UNLIMITED }
    private val _state = MutableStateFlow<UIState>(UIState.Loading)

    val state:StateFlow<UIState> get() = _state

    init {
        viewModelScope.launch {
            _intent.receiveAsFlow().collect{
                Log.i("message", "收到了内容: ")
                handleIntent(it)
            }
        }
    }

    abstract fun handleIntent(it: UIIntent)

    fun sendIntent(it:UIIntent){
        viewModelScope.launch {
            _intent.send(it)
        }
    }

    fun httpRequest(request:Flow<Res<Any>>, type: BaseType){
        viewModelScope.launch{
            request.flowOn(Dispatchers.IO)
                .catch {
                    LogUtils.e("网络请求异常${it.message}")
                }
                .collect {
                    _state.value = if (it.code==200){
                        UIState.Success(it.data,type)
                    }else{
                        UIState.Error(it.msg)
                    }
                }
        }
    }
}